from PyQt6.QtWidgets import QTreeWidget, QTreeWidgetItem, QPushButton
import json
import base64
import requests
from urllib import parse


class BookMarkWindow(QTreeWidget):

    def __init__(self, text: str, parent=None):
        super().__init__(parent)

        self.setObjectName(text)

        # 设置表头
        self.setColumnCount(2)
        self.setHeaderLabels(['名称', '地址'])
        self.setColumnWidth(0, 300)
        # self.setColumnWidth(1, 100)
        self.setAlternatingRowColors(True)

        # 初始化全局变量
        self.git_url = 'https://gitee.com/api'
        self.access_token = 'ff6bc95eb23af63b53ef25dfb89eea1e'
        self.owner = 'tf5488'
        self.repo = 'bookmark'
        self.path = 'bookmarks/'

        # 初始化根节点
        self.init_root_data()

    # 设置数节点头
    def init_root_data(self):
        # https://gitee.com/api/v5/repos/tf5488/bookmark/?access_token=ff6bc95eb23af63b53ef25dfb89eea1e&ref=master
        url = self.git_url + '/v5/repos/' + self.owner + '/' + self.repo + '/contents/' + self.path + '?access_token=' + self.access_token + '&ref=' + 'master'
        print('获取分支地址：', url)

        resp = requests.get(url)
        repoListJson = resp.json()

        index = 0
        repoList = []
        while index < len(repoListJson):
            repoList.append(repoListJson[index]['name'])
            root = QTreeWidgetItem(self)
            root.setText(0, repoListJson[index]['name'])

            # 初始化子类
            self._init_children(root)

            index = index + 1

        print('分支列表：', repoList)

    def _init_children(self, root: QTreeWidgetItem):
        fileStr = root.text(0)

        # 获取书签分支对应的书签信息
        fileUrl = self.git_url + '/v5/repos/' + self.owner + '/' + self.repo + '/contents/' + self.path + fileStr + '?access_token=' + self.access_token
        print('获取特定文件：', fileUrl)

        fileResp = requests.get(fileUrl)
        fileData = fileResp.json()

        # print('=fileData==:', fileData)
        # print('=content==:', fileData['content'])

        base64Str = base64.b64decode(fileData['content']).decode()
        # print("--解密1--", base64.b64decode(fileData['content']).decode())
        # print("--解密2--", parse.unquote(base64Str))

        a0 = parse.unquote(base64Str)
        self._init_tree(root, json.loads(a0))

    def _init_tree(self, root: QTreeWidgetItem, a0):
        index = 0
        while index < len(a0):
            info = a0[index]
            # 添加子节点
            child = QTreeWidgetItem(root)
            child.setText(0, info['title'])
            if 'url' in info:
                child.setText(1, info['url'])

            if 'children' in info:
                children = info['children']
                if len(children) != 0:
                    self._init_tree(child, children)
            index = index + 1
